package com.csust.automaticteach.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csust.automaticteach.common.BaseResponse;
import com.csust.automaticteach.common.ResultUtils;
import com.csust.automaticteach.exception.BusinessException;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.manager.cos.CosManager;
import com.csust.automaticteach.model.dto.generateteach.GenerateTeachFileRequest;
import com.csust.automaticteach.model.dto.generateteach.GenerateTeachQueryDTO;
import com.csust.automaticteach.model.dto.generateteach.GenerateTeachUpdateDTO;
import com.csust.automaticteach.model.entity.GenerateTeach;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.generateteach.GenerateTeachVO;
import com.csust.automaticteach.model.vo.generateteach.UploadReturnVO;
import com.csust.automaticteach.service.GenerateTeachService;
import com.csust.automaticteach.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import static com.csust.automaticteach.constant.FileConstant.FILE_CAN_NOT_BE_NULL;
import static com.csust.automaticteach.constant.FileConstant.FILE_FAIL_DELETE;

/**
 * @ClassNameGenerateTeachController
 * @Description 生成的教学大纲控制器
 * @Author钰玟
 * @Date2025/6/24 上午8:44
 * @Version 1.0
 **/
@RestController
@RequestMapping("generateTeach")
//@Tag(name = "教学内容接口", description = "教学内容接口")
public class GenerateTeachController {
    private static final Logger log = LoggerFactory.getLogger(GenerateTeachController.class);
    @Resource
    private GenerateTeachService generateTeachService;
    @Resource
    private UserService userService;
    @Resource
    private CosManager cosManager;


    @PostMapping("/upload")
    public BaseResponse<UploadReturnVO> uploadTeachFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        // 校验文件
        ThrowUtils.throwIf(file.isEmpty(), ErrorCode.PARAMS_ERROR, FILE_CAN_NOT_BE_NULL);
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        UploadReturnVO uploadReturnVO = generateTeachService.uploadTeachFile(file, loginUser);
        return ResultUtils.success(uploadReturnVO);
    }


    /**
     * 本地课程大纲
     *
     * @param generateTeachFileRequest 上传的文件
     * @return vo对象
     * @throws IOException 异常
     */
    @PostMapping("/generateTeachSyn")
//    @AuthCheck(mustRole = UserAuthConstant.TEACHER_ROLE)
    public BaseResponse<GenerateTeachVO> generateTeachFile(@RequestBody GenerateTeachFileRequest generateTeachFileRequest, HttpServletRequest request) throws IOException {
        //校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(generateTeachFileRequest), ErrorCode.PARAMS_ERROR, FILE_CAN_NOT_BE_NULL);
        User loginUser = userService.getLoginUser(request);
        GenerateTeachVO generateTeachVO = generateTeachService.generateTeachSyn(generateTeachFileRequest, loginUser);
        return ResultUtils.success(generateTeachVO);
    }

    /**
     * 异步生成课程大纲
     *
     * @param generateTeachFileRequest    上传的文件
     * @param request 请求
     * @return 大纲vo
     * @throws IOException 异常
     */
    @PostMapping("/generateTeachAsy")
//    @AuthCheck(mustRole = UserAuthConstant.TEACHER_ROLE)
    public BaseResponse<GenerateTeachVO> generateTeachFileAsy(@RequestBody GenerateTeachFileRequest generateTeachFileRequest
            , HttpServletRequest request) throws IOException {
        //校验参数
        ThrowUtils.throwIf(ObjUtil.isNull(generateTeachFileRequest), ErrorCode.PARAMS_ERROR, FILE_CAN_NOT_BE_NULL);
        User loginUser = userService.getLoginUser(request);
        GenerateTeachVO generateTeachVO = generateTeachService.generateTeachAsy(generateTeachFileRequest, loginUser);
        return ResultUtils.success(generateTeachVO);
    }


    /**
     * 获取课程大纲列表
     *
     * @param generateTeachQueryDTO 查询参数
     * @param request               请求
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<GenerateTeachVO>> listGenerateTeachVOByPage(@RequestBody GenerateTeachQueryDTO generateTeachQueryDTO
            , HttpServletRequest request) {
        ThrowUtils.throwIf(generateTeachQueryDTO == null, ErrorCode.PARAMS_ERROR);
        // 获取分页相关数据
        long current = generateTeachQueryDTO.getCurrent();
        long pageSize = generateTeachQueryDTO.getPageSize();

        //
        User loginUser = userService.getLoginUser(request);
        generateTeachQueryDTO.setUserId(loginUser.getId());
        //分页查询
        Page<GenerateTeach> generateTeachPage = generateTeachService.page(new Page<>(current, pageSize),
                generateTeachService.getGenerateTeachQueryWrapper(generateTeachQueryDTO));
        Page<GenerateTeachVO> generateTeachVOPage = new Page<>(current, pageSize, generateTeachPage.getTotal());
        List<GenerateTeachVO> generateTeachVOList = generateTeachService.getGenerateTeachVOList(generateTeachPage.getRecords());
        generateTeachVOPage.setRecords(generateTeachVOList);
        return ResultUtils.success(generateTeachVOPage);
    }

    /**
     * 获取某个详情课程大纲
     *
     * @param id 对应id
     * @return
     */
    @GetMapping("/get/{id}")
    public BaseResponse<GenerateTeachVO> getGenerateTeachVO(@PathVariable("id") Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        GenerateTeach generateTeach = generateTeachService.getById(id);
        GenerateTeachVO generateTeachVO = generateTeachService.getGenerateTeachVO(generateTeach);
        ThrowUtils.throwIf(generateTeach == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(generateTeachVO);
    }

    /**
     * 根据id删除课程大纲
     *
     * @param id id
     * @return boolean
     */
    @PostMapping("/delete/{id}")
    public BaseResponse<Boolean> deleteGenerateTeach(@PathVariable("id") Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        //从数据库中获取key (先获取url地址再截取key)
        GenerateTeach byId = generateTeachService.getById(id);
        String fileUrl = byId.getFileUrl();
        //https://automatic-teach-1325795131.cos.ap-guangzhou.myqcloud.com//user/1/2025-06-24_3040180999769259.doc
        String key = fileUrl.substring(fileUrl.lastIndexOf("//") + 1);
        try {
            cosManager.deleteFile(key);
        } catch (Exception e) {
            log.error("fail to delete the file,the reason is:" + e.getMessage());
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, FILE_FAIL_DELETE);
        }
        boolean result = generateTeachService.removeById(id);
        return ResultUtils.success(result);

    }

    /**
     * 修改教学内容
     *
     * @param generateTeachUpdateDTO dto
     * @return boolean
     */
    @PostMapping("/edit")
//    @AuthCheck(mustRole = UserAuthConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateGenerateTeach(@RequestBody GenerateTeachUpdateDTO generateTeachUpdateDTO) {
        //查看是否为空
        if (generateTeachUpdateDTO == null || generateTeachUpdateDTO.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        GenerateTeach generateTeach = new GenerateTeach();
        //设置摘要
        BeanUtils.copyProperties(generateTeachUpdateDTO, generateTeach);
        //设置修改时间
        generateTeach.setEditTime(new Date());
        //使用saveOrUpdate
        boolean result = generateTeachService.saveOrUpdate(generateTeach);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
